/**
 * 
 */
package fachkonzept;

import java.util.concurrent.ExecutionException;

import datenhaltung.IDatenhaltung;

import util.Car;
import util.Colour;
import util.EngineType;

/**
 * @author Sebastian
 * manages the saving transactions ordered by the carResultManager
 * and is able to reverse the last transaction
 */
class ReversableCarSaver implements ICarSaver {
	
	IDatenhaltung dataSource;
	Car carBeforeChange;
	/**
	 * create a new <code>ReversableCarSaver</code>
	 */
	ReversableCarSaver() {
		// TODO Auto-generated constructor stub
	}
	/**
	 * create a new <code>ReversableCarSaver</code>
	 * @param dataSource the data source to use
	 */
	ReversableCarSaver(IDatenhaltung dataSource) {
		
		this.dataSource = dataSource;
	}
	/**
	 * @return the dataSource
	 */
	IDatenhaltung getDataSource() {
		return dataSource;
	}
	/**
	 * @param dataSource the dataSource to set
	 */
	void setDataSource(IDatenhaltung dataSource) {
		this.dataSource = dataSource;
	}
	/**
	 * @return the carBeforeChange
	 */
	Car getCarBeforeChange() {
		return carBeforeChange;
	}
	/**
	 * @param carBeforeChange the carBeforeChange to set
	 */
	void setCarBeforeChange(Car carBeforeChange) {
		this.carBeforeChange = carBeforeChange;
	}
	/* (non-Javadoc)
	 * @see fachkonzept.ICarSaver#saveCar(java.lang.String, util.Colour, util.EngineType, int, double, double, int, boolean)
	 */
	@Override
	public void saveCar(String identificationNumber, Colour theColour,
			EngineType theEngineType, int yearOfConstruction, double originPrice,
			double price, int mileage, boolean isSelled, String carType, String manufacturer, String model)
			throws ExecutionException {
		
		Car carToSave = new Car(
				identificationNumber, 
				theColour,
				theEngineType, 
				yearOfConstruction, 
				originPrice, 
				price,
				mileage, 
				isSelled,
				carType,
				manufacturer,
				model);
		Car carToStoreCondition = new Car();
		carToStoreCondition.setIdentificationNumber(identificationNumber);
		Car[] searchResultArray = dataSource.getCars(carToStoreCondition);
		if( searchResultArray!=null && searchResultArray.length != 0 ){
			carBeforeChange = searchResultArray[0];
		}
		else{
			carBeforeChange = null;
		}
		dataSource.saveCar(carToSave);
	}
	/**
	 * makes the last erase undone and undeletes the last deleted car
	 */
	void undoLastSave() throws ExecutionException{
		
		if(carBeforeChange==null) {
			
			dataSource.deleteCar(carBeforeChange.getIdentificationNumber());
		}
		else{
			dataSource.saveCar(carBeforeChange);
		}
	}
	
}
